﻿using System;
using System.Windows.Media.Imaging;

namespace POBR.ImageProcessor
{
	public class ImageProcessor
	{
		private readonly Binarizer _binarizer = new Binarizer();
		private readonly Segmentator _segmentator = new Segmentator();
		private readonly SegmentFilter _segmentFilter = new SegmentFilter();

		public BitmapSource Process(BitmapSource bitmap)
		{
			if (bitmap == null)
				throw new ArgumentNullException("bitmap");

			var bytesCount = bitmap.PixelWidth * bitmap.PixelHeight * 4;	
			var pixels = new byte[bytesCount];
			bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0);

			var result = ProcessPicture(new Picture(bitmap.PixelWidth, bitmap.PixelHeight, pixels));

			return BitmapSource.Create(bitmap.PixelWidth, bitmap.PixelHeight, bitmap.DpiX, bitmap.DpiY,
									   bitmap.Format, bitmap.Palette, result.Pixels, result.Width * 4);
		}

		private Picture ProcessPicture(Picture picture)
		{
			var binarizedPicture = _binarizer.Binarize(picture);
			var segments = _segmentator.DivideIntoSegments(binarizedPicture);
			var filteredSegments = _segmentFilter.FilterSegments(binarizedPicture, segments);

			foreach (var segment in filteredSegments)
			{
				for (int x = segment.X; x != segment.X + segment.Width; ++x)
				{
					for (int y = segment.Y; y != segment.Y + segment.Height; ++y)
					{
						binarizedPicture.SetGreen(x, y);
					}
				}
			}

			/*
			for (int x = 0; x != binarizedPicture.Width; x++)
			{
				for (int y = 0; y != binarizedPicture.Height; y++)
				{
					if (false == filteredSegments.Any(s => x >= s.X && x < s.X + s.Width && y >= s.Y && y < s.Y + s.Height))
						binarizedPicture.SetBlack(x, y);
				}
			}
			*/

			return binarizedPicture;
		}
	}
}
